import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'tracking_model.dart';

class RankingInfoPage extends StatefulWidget {
  const RankingInfoPage({super.key});

  @override
  State<RankingInfoPage> createState() => _RankingInfoPageState();
}

class _RankingInfoPageState extends State<RankingInfoPage> {
  final TextEditingController _numberController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  String _selectedCompany = 'auto';
  bool _isLoading = false;
  TrackingResponse? _trackingResponse;
  String? _errorMessage;

  final List<Map<String, String>> _companies = [
    {'code': 'auto', 'name': '自动识别'},
    {'code': 'yt', 'name': '圆通快递'},
    {'code': 'yd', 'name': '韵达快递'},
    {'code': 'sf', 'name': '顺丰速运'},
    {'code': 'zto', 'name': '中通快递'},
    {'code': 'ems', 'name': 'EMS'},
    {'code': 'yunda', 'name': '韵达快递'},
    {'code': 'jd', 'name': '京东物流'},
    {'code': 'ups', 'name': 'UPS'},
    {'code': 'fedex', 'name': 'FedEx'},
    {'code': 'dhl', 'name': 'DHL'},
  ];

  Future<void> _queryTracking() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
      _trackingResponse = null;
    });

    final number = _numberController.text.trim();
    if (number.isEmpty) {
      setState(() {
        _isLoading = false;
        _errorMessage = '请输入快递单号';
      });
      return;
    }

    // 顺丰需要手机号后四位
    final phone = _phoneController.text.trim();
    if (_selectedCompany == 'sf' && phone.isEmpty) {
      setState(() {
        _isLoading = false;
        _errorMessage = '顺丰快递需要输入手机号后四位';
      });
      return;
    }

    try {
      final response = await http.post(
        Uri.parse('https://v3.alapi.cn/api/tracking'),
        body: {
          'token': 'ycd0krwbhl5v2w6iafblj94y5vzqdj',
          'number': number,
          'com': _selectedCompany,
          'phone': phone,
        },
      );

      if (response.statusCode == 200) {
        final jsonData = json.decode(response.body);
        if (jsonData['code'] == 200) {
          setState(() {
            _trackingResponse = TrackingResponse.fromJson(jsonData);
            _isLoading = false;
          });
        } else {
          setState(() {
            _isLoading = false;
            _errorMessage = jsonData['message'] ?? '查询失败';
          });
        }
      } else {
        setState(() {
          _isLoading = false;
          _errorMessage = '网络请求失败，状态码：${response.statusCode}';
        });
      }
    } catch (e) {
      setState(() {
        _isLoading = false;
        _errorMessage = '发生错误：$e';
      });
    }
  }

  @override
  void dispose() {
    _numberController.dispose();
    _phoneController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: const Text('快递查询助手'),
        backgroundColor: Theme.of(context).colorScheme.primary,
        foregroundColor: Colors.white,
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              // 输入区域
              Card(
                elevation: 4,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      TextField(
                        controller: _numberController,
                        decoration: const InputDecoration(
                          labelText: '快递单号',
                          hintText: '请输入快递单号',
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.qr_code),
                        ),
                      ),
                      const SizedBox(height: 16),
                      DropdownButtonFormField<String>(
                        decoration: const InputDecoration(
                          labelText: '快递公司',
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.local_shipping),
                        ),
                        value: _selectedCompany,
                        items: _companies.map((company) {
                          return DropdownMenuItem(
                            value: company['code'],
                            child: Text(company['name']!),
                          );
                        }).toList(),
                        onChanged: (value) {
                          setState(() {
                            _selectedCompany = value!;
                          });
                        },
                      ),
                      const SizedBox(height: 16),
                      TextField(
                        controller: _phoneController,
                        decoration: InputDecoration(
                          labelText: '手机号后四位${_selectedCompany == 'sf' ? '（必填）' : '（选填）'}',
                          hintText: '顺丰快递需要填写',
                          border: const OutlineInputBorder(),
                          prefixIcon: const Icon(Icons.phone_android),
                        ),
                        keyboardType: TextInputType.number,
                        maxLength: 4,
                      ),
                      const SizedBox(height: 16),
                      SizedBox(
                        height: 50,
                        child: ElevatedButton(
                          onPressed: _isLoading ? null : _queryTracking,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Theme.of(context).colorScheme.primary,
                            foregroundColor: Colors.white,
                          ),
                          child: _isLoading
                              ? const CircularProgressIndicator(color: Colors.white)
                              : const Text('查询快递'),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 16),
              // 错误信息
              if (_errorMessage != null)
                Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: Colors.red.shade100,
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Text(
                    _errorMessage!,
                    style: TextStyle(color: Colors.red.shade900),
                  ),
                ),
              // 查询结果
              if (_trackingResponse != null && _trackingResponse!.success)
                SizedBox(
                  height: 400, // 给结果区域一个固定高度
                  child: _buildTrackingResult(),
                ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTrackingResult() {
    final data = _trackingResponse!.data;
    return Card(
      elevation: 4,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 快递信息头部
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.primaryContainer,
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(12),
                topRight: Radius.circular(12),
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      data.expName,
                      style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    _buildStatusChip(data.status),
                  ],
                ),
                const SizedBox(height: 8),
                Text('单号：${data.number}'),
              ],
            ),
          ),
          // 物流轨迹 - 这里是问题所在，需要使用 Expanded
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.all(16),
              itemCount: data.info.length,
              itemBuilder: (context, index) {
                final info = data.info[index];
                final bool isFirst = index == 0;
                final bool isLast = index == data.info.length - 1;
                
                return Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Column(
                      children: [
                        Container(
                          width: 20,
                          height: 20,
                          decoration: BoxDecoration(
                            color: isFirst
                                ? Theme.of(context).colorScheme.primary
                                : Colors.grey,
                            shape: BoxShape.circle,
                          ),
                          child: isFirst
                              ? const Icon(Icons.check, size: 12, color: Colors.white)
                              : null,
                        ),
                        if (!isLast)
                          Container(
                            width: 2,
                            height: 60,
                            color: Colors.grey.shade300,
                          ),
                      ],
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            info.time,
                            style: TextStyle(
                              color: isFirst ? Theme.of(context).colorScheme.primary : Colors.grey,
                              fontWeight: isFirst ? FontWeight.bold : FontWeight.normal,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            info.content,
                            style: TextStyle(
                              color: isFirst ? Colors.black : Colors.grey.shade700,
                              fontWeight: isFirst ? FontWeight.bold : FontWeight.normal,
                            ),
                          ),
                          const SizedBox(height: 16),
                        ],
                      ),
                    ),
                  ],
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStatusChip(int status) {
    Color chipColor;
    String statusText;
    
    switch (status) {
      case 0:
        chipColor = Colors.blue;
        statusText = '在途';
        break;
      case 1:
        chipColor = Colors.orange;
        statusText = '揽件';
        break;
      case 2:
        chipColor = Colors.red;
        statusText = '问题件';
        break;
      case 3:
        chipColor = Colors.green;
        statusText = '已签收';
        break;
      case 4:
        chipColor = Colors.purple;
        statusText = '退签';
        break;
      case 5:
        chipColor = Colors.teal;
        statusText = '派件';
        break;
      case 6:
        chipColor = Colors.brown;
        statusText = '退回';
        break;
      default:
        chipColor = Colors.grey;
        statusText = '未知';
    }
    
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      decoration: BoxDecoration(
        color: chipColor.withOpacity(0.2),
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: chipColor, width: 1.5),
      ),
      child: Text(
        statusText,
        style: TextStyle(color: chipColor, fontWeight: FontWeight.bold),
      ),
    );
  }
}